package search;

import java.util.Arrays;

public class FibSearch {

    private static int maxSize = 20;

    public static void main(String[] args) {
        int arr[] = {2};
     //   System.out.println(Arrays.toString(fibArr()));
        System.out.println(search(arr, 2));
    }

    private static int[] fibArr() {
        int arr[] = new int[maxSize];
        arr[0] = 0;
        arr[1] = 1;
        for (int i = 2; i < maxSize; i++) {
            arr[i] = arr[i - 1] + arr[i - 2];
        }
        return arr;
    }

    // 返回下标
    private static int search(int arr[], int findVal) {
        int fibarr[] = fibArr();
        // 补全数组
        int k = 0;
        while (arr.length > fibarr[k]) {
            k++;
        }
        int temp[] = Arrays.copyOf(arr, fibarr[k]);

        int left = 0;
        int right = fibarr[k] - 1;
        int mid = -1;
        // 左半 f[k-1] 个，右半 f[k-2] 个
        //
        while (left <= right) {
            mid = left + fibarr[k-1]; // mid 为 右半部分第一个, 用fibarr[k]表示当前长度
            if (findVal == temp[mid]) {
                // 如果找的是 0，对比 mid 与 arr.length
                if (mid < arr.length) {
                    return mid;
                } else {
                    return -1;
                }
            } else if (findVal < temp[mid]) { // 左半部分
                right = mid - 1;
                k--;
            } else {
                left = mid;
                k-=2;
            }
        }

        return -1;
    }
}
